<template>
  <view class="analysis-container">
    <!-- 脉象信息 -->
    <view v-if="reportData.pulse_info" class="section">
      <view class="section-header" @click="toggleSection('pulse')">
        <text class="section-title">{{ $t('report.pulse_info') }}</text>
        <view class="collapse-icon" :class="{ collapsed: collapsedSections.pulse }">
          <text class="icon-text">{{ collapsedSections.pulse ? '▲' : '▼' }}</text>
        </view>
      </view>
      <view v-show="!collapsedSections.pulse" class="section-content">
        <view class="pulse-info">
          <!-- 脉象图表 -->
          <view v-if="reportData.pulse_info" class="pulse-charts">
            <!-- 左右手脉象图表 Tab -->
            <view class="tabs-container">
              <view
                class="tab-button"
                :class="{ active: activePulseHandTab === 'left' }"
                v-if="hasLeftPulseData"
                @click="activePulseHandTab = 'left'">
                {{ $t('report.left_pulse') }}
              </view>
              <view
                class="tab-button"
                :class="{ active: activePulseHandTab === 'right' }"
                v-if="hasRightPulseData"
                @click="activePulseHandTab = 'right'">
                {{ $t('report.right_pulse') }}
              </view>
            </view>

            <!-- 寸关尺脉象图表 -->
            <view class="chart-wrapper" v-if="activePulseHandTab === 'left' && hasLeftPulseData">
              <BaseCharts :option="pulseChartOptionLeft" />
            </view>
            <view class="chart-wrapper" v-if="activePulseHandTab === 'right' && hasRightPulseData">
              <BaseCharts :option="pulseChartOptionRight" />
            </view>
          </view>

          <!-- 脉象类型标签 -->
          <view
            class="pulse-result-box"
            v-if="
              reportData.pulse_info.left_pulse_info.details && reportData.pulse_info.left_pulse_info.details.length > 0
            ">
            <view class="tabs-container">
              <view
                v-for="(pulse, index) in pulseTypes"
                :key="index"
                class="tab-button"
                :class="{ active: activeTabIndex === index }"
                @click="setActiveTab(index)">
                {{ pulse.label }}<text class="tab-value">{{ pulse.value }}</text>
              </view>
            </view>

            <!-- 脉象详情描述 -->
            <view class="details-container">
              <text class="details-text">{{ activePulseDetail }}</text>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 调理建议（富文本展示） -->
    <view
      v-if="
        reportData.pulse_info &&
        reportData.pulse_info.left_pulse_info.details &&
        reportData.pulse_info.left_pulse_info.details.length > 0
      "
      class="section">
      <view class="section-header" @click="toggleSection('suggest')">
        <text class="section-title">{{ $t('report.pulse_suggest') }}</text>
        <view class="collapse-icon" :class="{ collapsed: collapsedSections.suggest }">
          <text class="icon-text">{{ collapsedSections.suggest ? '▲' : '▼' }}</text>
        </view>
      </view>
      <view v-show="!collapsedSections.suggest" class="section-content">
        <view class="suggest-content">
          <rich-text v-if="firstPulseSuggest" :nodes="firstPulseSuggest" @error="handleRichTextError"></rich-text>
          <text v-else class="no-suggest-text">{{ $t('report.no_suggest') }}</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
  // 1. 引入 onMounted 和 onUnload (或使用 uniapp 的 onLoad)
  import { ref, computed, onMounted, watch } from 'vue'
  import { useI18n } from 'vue-i18n'
  import BaseCharts from './BaseCharts.vue'
  import { onLoad } from '@dcloudio/uni-app'
  import { getPulseDiagnosisResult } from '@/api/acupoint.js'
  const { t } = useI18n()
  // --- 状态管理 ---
  const activeTabIndex = ref(0)
  const activePulseHandTab = ref('left')
  // --- 数据处理 ---
  // 3. 将 chartData 初始化为 null，等待从缓存加载
  const reportData = ref({})
  const appointNo = ref('')
  // 折叠状态管理
  const collapsedSections = ref({
    tongue: false, // 舌诊信息
    face: false, // 面诊信息
    pulse: false, // 脉诊信息
    suggest: false // 调理建议
  })

  onLoad(option => {
    appointNo.value = option.appointNo
  })

  // 4. 使用 onMounted 生命周期钩子从缓存获取数据
  onMounted(async () => {
    //new VConsole()

    uni.setNavigationBarTitle({
      title: t('pulseAnalysis.title')
    })
    try {
      uni.showLoading({ title: t('common.loading') })
      const res = await getPulseDiagnosisResult(appointNo.value)
      uni.hideLoading()

      if (res && res.result) {
        console.log('数据', res)
        reportData.value = {
          pulse_info: res.result
        }
      } else {
        uni.showToast({
          title: t('pulseAnalysis.dataLoadFailed'),
          icon: 'none'
        })
      }
    } catch (error) {
      uni.hideLoading()
      uni.showToast({
        title: t('pulseAnalysis.dataLoadFailed'),
        icon: 'none'
      })
      console.error('getPulseDiagnosisResult error:', error)
    }
  })
  // 当数据加载后，设置默认显示的手部 Tab
  watch(
    () => reportData.value?.pulse_info,
    () => {
      if (hasLeftPulseData.value) {
        activePulseHandTab.value = 'left'
      } else if (hasRightPulseData.value) {
        activePulseHandTab.value = 'right'
      }
    }
  )

  // 左右手数据可用性
  const hasLeftPulseData = computed(() => !!reportData.value?.pulse_info?.left_pulse_info)
  const hasRightPulseData = computed(() => !!reportData.value?.pulse_info?.right_pulse_info)

  // 提取脉象类型用于渲染标签
  const pulseTypes = computed(() => {
    if (!reportData.value?.pulse_info?.left_pulse_info.details) {
      return []
    }

    return reportData.value.pulse_info.left_pulse_info.details.map(detail => {
      const score = detail.score || detail.pulse_type
      const label = score.replace(/[0-9]/g, '') // 移除数字得到文字
      const value = score.replace(/[^0-9]/g, '') // 移除文字得到数字
      return {
        label: label,
        value: value
      }
    })
  })

  // 获取当前激活的脉象描述
  const activePulseDetail = computed(() => {
    if (
      !reportData.value?.pulse_info?.left_pulse_info.details ||
      activeTabIndex.value >= reportData.value.pulse_info.left_pulse_info.details.length
    ) {
      return t('pulseAnalysis.noData')
    }
    return reportData.value.pulse_info.left_pulse_info.details[activeTabIndex.value].pulse_condition
  })

  const activePulsepulse_suggest = computed(() => {
    // 已有的安全检查，无需改动
    if (!chartData.value || !chartData.value.details || activeTabIndex.value >= chartData.value.details.length) {
      return t('pulseAnalysis.noData')
    }

    return chartData.value.details[activeTabIndex.value].pulse_suggest
  })

  // 构建脉象图表配置（寸、关、尺三线）
  const buildPulseChartOption = pulseSideInfo => {
    if (!pulseSideInfo) return null

    const cunData = pulseSideInfo.cun_data || []
    const guanData = pulseSideInfo.guan_data || []
    const chiData = pulseSideInfo.chi_data || []

    const maxLength = Math.max(cunData.length, guanData.length, chiData.length)
    const xAxisData = Array.from({ length: maxLength }, (_, i) => i + 1)

    const allData = [...cunData, ...guanData, ...chiData]
    if (allData.length === 0) return null
    const dataMin = Math.min(...allData)
    const dataMax = Math.max(...allData)
    const yMin = Math.floor(dataMin / 20) * 20 - 20
    const yMax = Math.ceil(dataMax / 20) * 20 + 20

    return {
      tooltip: {
        trigger: 'axis',
        backgroundColor: 'rgba(255, 255, 255, 0.95)',
        borderColor: '#ddd',
        borderWidth: 1,
        textStyle: {
          color: '#333',
          fontSize: 12
        },
        formatter: function (params) {
          let result = `<div style="font-weight: bold; margin-bottom: 8px;">${t('report.pulse_info')}</div>`
          params.forEach(param => {
            result += `<div style="display: flex; justify-content: space-between; margin: 4px 0;">
            <span style=\"color: ${param.color}; margin-right: 10px;\">●</span>
            <span style=\"margin-right: 10px;\">${param.seriesName}:</span>
            <span style=\"font-weight: bold;\">${param.value}</span>
          </div>`
          })
          return result
        }
      },
      legend: {
        data: [
          { name: t('blueIndex.legendCun'), icon: 'circle' },
          { name: t('blueIndex.legendGuan'), icon: 'circle' },
          { name: t('blueIndex.legendChi'), icon: 'circle' }
        ],
        top: '5%',
        left: 'center',
        itemWidth: 10,
        itemHeight: 10,
        textStyle: {
          fontSize: 12,
          color: '#333'
        },
        itemGap: 30
      },
      grid: {
        left: '13%',
        right: '5%',
        bottom: '10%',
        top: '25%',
        containLabel: false
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: xAxisData,
        axisLine: {
          lineStyle: { color: '#ccc', width: 1 }
        },
        axisTick: {
          show: true,
          alignWithLabel: true,
          lineStyle: { color: '#ccc' }
        },
        axisLabel: {
          interval: (index, value) => index % Math.ceil(maxLength / 10) === 0,
          color: '#666',
          fontSize: 10
        }
      },
      yAxis: {
        type: 'value',
        min: yMin,
        max: yMax,
        interval: Math.ceil((yMax - yMin) / 6),
        axisLine: {
          show: true,
          lineStyle: { color: '#ccc', width: 1 }
        },
        axisTick: {
          lineStyle: { color: '#ccc' }
        },
        axisLabel: {
          color: '#666',
          fontSize: 10
        },
        splitLine: {
          show: false
        }
      },
      series: [
        {
          name: t('blueIndex.legendCun'),
          type: 'line',
          smooth: true,
          smoothMonotone: 'x',
          showSymbol: false,
          symbol: 'none',
          symbolSize: 0,
          data: cunData,
          lineStyle: { color: '#ff4757', width: 1.5 },
          itemStyle: { color: '#ff4757' },
          emphasis: {
            focus: 'series',
            lineStyle: { width: 2.0 },
            showSymbol: false,
            symbol: 'none',
            symbolSize: 0
          },
          animationDuration: 2000,
          animationEasing: 'cubicOut'
        },
        {
          name: t('blueIndex.legendGuan'),
          type: 'line',
          smooth: true,
          smoothMonotone: 'x',
          showSymbol: false,
          symbol: 'none',
          symbolSize: 0,
          data: guanData,
          lineStyle: { color: '#3742fa', width: 1.5 },
          itemStyle: { color: '#3742fa' },
          emphasis: {
            focus: 'series',
            lineStyle: { width: 2.0 },
            showSymbol: false,
            symbol: 'none',
            symbolSize: 0
          },
          animationDuration: 2000,
          animationEasing: 'cubicOut'
        },
        {
          name: t('blueIndex.legendChi'),
          type: 'line',
          smooth: true,
          smoothMonotone: 'x',
          showSymbol: false,
          symbol: 'none',
          symbolSize: 0,
          data: chiData,
          lineStyle: { color: '#2ed573', width: 1.5 },
          itemStyle: { color: '#2ed573' },
          emphasis: {
            focus: 'series',
            lineStyle: { width: 2.0 },
            showSymbol: false,
            symbol: 'none',
            symbolSize: 0
          },
          animationDuration: 2000,
          animationEasing: 'cubicOut'
        }
      ]
    }
  }

  const pulseChartOptionLeft = computed(() => {
    if (!hasLeftPulseData.value) return null
    return buildPulseChartOption(reportData.value.pulse_info.left_pulse_info)
  })

  const pulseChartOptionRight = computed(() => {
    if (!hasRightPulseData.value) return null
    return buildPulseChartOption(reportData.value.pulse_info.right_pulse_info)
  })
  // 切换折叠状态
  const toggleSection = sectionKey => {
    collapsedSections.value[sectionKey] = !collapsedSections.value[sectionKey]
  }
  // --- 方法 ---
  function setActiveTab(index) {
    activeTabIndex.value = index
  }
  // 清理HTML内容，移除Office特有的标签
  const cleanHtml = html => {
    if (!html) return ''

    return (
      html
        // 移除Office特有的标签
        .replace(/<o:[^>]*>/g, '')
        .replace(/<\/o:[^>]*>/g, '')
        // 移除Word特有的注释
        .replace(/<!--\[if[^>]*>.*?<!\[endif\]-->/g, '')
        // 移除MsoNormal类名，保留p标签
        .replace(/class="MsoNormal"/g, '')
        // 移除font标签，保留内容
        .replace(/<font[^>]*>/g, '')
        .replace(/<\/font>/g, '')
        // 移除span标签，保留内容
        .replace(/<span[^>]*>/g, '')
        .replace(/<\/span>/g, '')
        // 移除b标签，保留内容
        .replace(/<b[^>]*>/g, '<strong>')
        .replace(/<\/b>/g, '</strong>')
        // 移除h3标签，保留内容
        .replace(/<h3[^>]*>/g, '<h3>')
        .replace(/<\/h3>/g, '</h3>')
        // 清理多余的空白字符
        .replace(/\s+/g, ' ')
        // 清理多余的换行
        .replace(/\n+/g, '\n')
        // 确保HTML结构完整
        .replace(/<p[^>]*>\s*<\/p>/g, '') // 移除空段落
        .trim()
    )
  }

  // 获取第一个脉象建议（富文本）
  const firstPulseSuggest = computed(() => {
    //   console.log('firstPulseSuggest computed:', reportData.value?.pulse_info?.details)
    if (
      !reportData.value?.pulse_info?.left_pulse_info.details ||
      reportData.value.pulse_info.left_pulse_info.details.length === 0
    ) {
      // console.log('No pulse details found')
      return null
    }
    const suggest = reportData.value.pulse_info.left_pulse_info.details[0].pulse_suggest

    // 清理HTML内容
    const cleanedSuggest = cleanHtml(suggest)

    return cleanedSuggest
  })

  // 处理富文本渲染错误
  const handleRichTextError = error => {
    console.error('Rich text rendering error:', error)
    // 如果富文本渲染失败，可以尝试显示纯文本
    uni.showToast({
      title: t('report.render_error'),
      icon: 'none',
      duration: 2000
    })
  }
  function goBack() {
    uni.navigateBack()
  }
</script>

<style lang="scss" scoped>
  page {
    background-color: #f0f0f0;
  }

  .analysis-container {
    padding: 20rpx;

    background-color: #f0f0f0;
    .section {
      background-color: white;
      border-radius: 10px;
      padding: 20px;
      margin-bottom: 15px;
      border: 1px solid #eee;

      .section-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        border-bottom: 1px solid #eee;
        padding-bottom: 10px;
        margin-bottom: 15px;
        cursor: pointer;
        user-select: none;

        .section-title {
          font-size: 18px;
          font-weight: bold;
          color: #333;
        }

        .collapse-icon {
          width: 24px;
          height: 24px;
          display: flex;
          align-items: center;
          justify-content: center;
          border-radius: 50%;
          background-color: #f5f5f5;
          transition: all 0.3s ease;

          .icon-text {
            font-size: 12px;
            color: #666;
            transition: transform 0.3s ease;
          }

          &.collapsed {
            .icon-text {
              transform: rotate(180deg);
            }
          }

          &:hover {
            background-color: #e9e9e9;
          }
        }
      }

      .section-content {
        transition: all 0.3s ease;
      }
    }
  }

  // 仿写顶部导航栏
  .page-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 20rpx;
    background-color: #f8f8f8;
    border-bottom: 1rpx solid #eee;

    .back-button {
      font-size: 44rpx;
      color: #333;
      font-weight: bold;
    }

    .title {
      font-size: 34rpx;
      font-weight: bold;
      color: #000;
    }

    .right-icons {
      display: flex;
      align-items: center;
      gap: 30rpx;

      .icon-item {
        font-size: 40rpx;
        font-weight: bold;
      }

      .camera {
        width: 40rpx;
        height: 40rpx;
        border: 4rpx solid #000;
        border-radius: 50%;
        position: relative;

        &::after {
          content: '';
          position: absolute;
          top: 50%;
          left: 50%;
          transform: translate(-50%, -50%);
          width: 16rpx;
          height: 16rpx;
          background-color: #000;
          border-radius: 50%;
        }
      }
    }
  }

  .chart-wrapper {
    height: 400rpx;
    width: 100%;
    background-color: #fff;
    border-radius: 16rpx;
    margin-top: 20rpx;
    padding: 10rpx;
    box-sizing: border-box;
  }

  .pulse-result-box {
    background-color: #fff;
    border-radius: 16rpx;
    margin-top: 20rpx;
    padding: 30rpx;
  }

  .tabs-container {
    display: flex;
    justify-content: space-around;
    border-bottom: 2rpx solid #f0f0f0;
    padding-bottom: 20rpx;
    margin-bottom: 20rpx;
  }

  .tab-button {
    padding: 10rpx 15rpx;
    font-size: 30rpx;
    color: #888;
    border-radius: 8rpx;
    background-color: transparent;
    transition: all 0.3s;
    border-bottom: 6rpx solid transparent;
    font-weight: 500;

    &.active {
      color: #333;
      border-bottom-color: #4e7afb;
      font-weight: bold;
    }

    .tab-value {
      font-size: 26rpx;
      margin-left: 2rpx;
    }
  }

  .details-container {
    padding-top: 10rpx;

    .details-text {
      font-size: 28rpx;
      line-height: 1.7;
      color: #666;
      text-align: justify;
    }
    .section-title {
      font-size: 16px;
      font-weight: bold;
      color: #1296db;
      margin: 10px 0;
      margin-top: 30px;
    }
  }
</style>
